/**
 * 判断传入String对象是否为空
 * @param obj
 * @returns
 */
export const isNullObject = (obj: string | any) => {
    if (typeof obj === 'string') {
        return obj === '{}' || obj === '[]';
    }
    return false;
};

/**
 * JSON转换器，不会抛出异常
 * @param json JSON内容
 * @param defaultValue 默认值
 */
export const parseJSONSafety = (json: string | any, defaultValue?: any) => {
    if (typeof json === 'string') {
        try {
            return JSON.parse(json);
        } catch (e) {
            console.warn(e);
            return defaultValue;
        }
    }
    if (json == null && defaultValue) return defaultValue;
    return json;
};

/**
 * 移除对象中的无效键和空串键
 * @param obj
 * @param options
 * @returns {*}
 */
export function removeEmptyProperties(
    obj: Record<string, any>,
    options: {
        ignores?: string[];
        trim?: boolean;
        deep?: boolean;
    } = {},
): Record<string, any> | null {
    if (!obj) return null;
    Object.keys(obj).forEach((key: string) => {
        const { ignores, deep = true } = options;
        let val = obj[key];
        if (ignores && ignores.indexOf(key) !== -1) {
            return;
        }
        if (options.trim && typeof val === 'string') {
            val = val.trim();
            obj[key] = val;
        }
        if (val == null || val === '') {
            obj[key] = undefined;
            delete obj[key];
        }
        if (deep && typeof val === 'object') {
            removeEmptyProperties(val, options);
        }
    });
    return obj;
}

/**
 * 移除对象中指定的属性
 * @param obj 操作对象
 * @param shouldRemoveProps 需要移除的字段
 */
export const removeProperties = (obj: any, shouldRemoveProps: string[]): any => {
    if (!shouldRemoveProps.length) return obj;
    Object.keys(obj).forEach((key: string) => {
        if (shouldRemoveProps.includes(key)) {
            obj[key] = undefined;
            delete obj[key];
        } else if (typeof obj[key] === 'object') {
            removeProperties(obj[key], shouldRemoveProps);
        }
    });
    return obj;
};

/**
 * 对象转数组map {id: 1} => [{id: 1}]
 * @param object
 */
export const transformedObjectToArray = (object: object): object[] => {
    const array = [];
    for (const key in object) {
        array.push({ [key]: object[key] });
    }
    return array;
};

/**
 * 获取对象所有values
 * @param {*} object 对象
 */
export const getObjectValues = (object: any): any[] => {
    return Object.values(object);
};

/**
 * 判断key是否在对象中
 * @param obj
 * @param key
 */
export const isKeyInObject = (obj: object, key: string): boolean => {
    return key in obj;
};
